<template>
  <div class="fixed right-4 top-4" v-if="logText || showUpdate">
    <!-- 更新进度提示 -->
    <div v-if="logText && !showUpdate" class="update-alert">
      <div class="alert-content">
        <span class="alert-label">插件包：</span>
        <span class="alert-text">{{ logText }}</span>
      </div>
      <button @click="closeAlert" class="close-btn">×</button>
    </div>

    <!-- 更新提示卡片 -->
    <div v-if="showUpdate" class="update-card">
      <div class="card-header">
        <h3>发现新版本插件包</h3>
        <!-- <button @click="closeUpdate" class="close-btn">×</button> -->
      </div>

      <div class="card-body">
        <!-- 非强制更新：显示倒计时并自动重启 -->
        <div class="normal-update">
          <p class="update-message">
            系统将在 <span class="countdown">{{ countdown }}</span> 秒后自动重启
          </p>
          <div class="button-group">
            <button @click="resetCountdown" class="btn btn-secondary">
              重置倒计时
            </button>
            <button @click="confirmUpdate" class="btn btn-primary">
              立即更新
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import getAstsdk from "ast_sdk";
import { onMounted, onUnmounted, ref } from "vue";
import orgApi from "../apis/orgApis/orgApi";

// 插件包状态提示语
const logText = ref<string>("");
// 展示询问是否更新的弹窗
const showUpdate = ref<boolean>(false);
// 是否强制更新
const isForceUpdate = ref<boolean>(false);
// 倒计时秒数
const countdown = ref<number>(60);
// 关闭弹窗的定时器
let closeTimer: ReturnType<typeof setTimeout>;
// 倒计时定时器
let countdownTimer: ReturnType<typeof setInterval> | null = null;
let isDownloadFailed = false;
let _isForce = false;

// 处理插件更新的函数
const handlePluginUpdate = async (
  downloadUrl: string,
  isForce: boolean
): Promise<void> => {
  try {
    // 2.尝试下载插件包
    _isForce = isForce;
    getAstsdk()
      .getAppFun()
      .requestUpMiniPack({ retryCount: 10, url: downloadUrl, isForce });
  } catch (error) {
    console.error("请求下载插件包更新失败", error);
    throw error;
  }
};

/**
 * 监听插件包更新状态
 */
const bc = (data: PluginUpdateState) => {
  try {
    console.log("插件包更新状态:", data);

    if (data.progress === -1) {
      if (isDownloadFailed === true) {
        return;
      }
      logText.value = data.log;
      isDownloadFailed = true;
      throw new Error(data.log);
    }

    if (closeTimer) clearTimeout(closeTimer);

    switch (data.state) {
      case 1000: // 加载插件包信息
        console.log("正在加载插件包信息");
        logText.value = "";
        break;

      case 7000:
        if (data.progress === 2) {
          // 如果进度是2 则是说明插件只使用本地插件那么就不要提示了
          showUpdate.value = false;
          logText.value = "";
          break;
        }
        if (data.log === "资源载入失败" || data.log === "资源预载入失败1") {
          showUpdate.value = false;
          logText.value = "";
          break;
        }
        console.log("插件包更新完成");
        if (_isForce === true) {
          // 强制更新时不显示任何提示，由安卓端处理
          showUpdate.value = false;
          logText.value = "";
        } else {
          // 非强制更新时显示倒计时并自动重启
          isForceUpdate.value = false;
          showUpdate.value = true;
          startCountdown();
        }
        break;

      default:
        // 更新进度提示
        logText.value = data.log;
        console.log("更新进度:", data);
        closeTimer = setTimeout(() => {
          logText.value = "";
        }, 2000);
    }
  } catch (error) {
    console.error("插件包更新事件订阅失败", error);
    logText.value = "插件包更新事件订阅失败";
    closeTimer = setTimeout(() => {
      logText.value = "";
    }, 2000);
  }
};

// 获取插件更新配置的封装函数
const fetchPluginUpdateConfig = async () => {
  try {
    // 从后台获取插件包的地址
    const { deviceUncode } = await getAstsdk().getInfo().getBaseInfo();
    console.log("debugger：插件更新--设备唯一码:", deviceUncode);

    const ca = await orgApi.config_app({ uniqueCode: deviceUncode });
    console.log("debugger：插件配置信息:", ca);

    if (ca.file && Array.isArray(ca.file) && ca.file?.[0]) {
      let downloadUrl = ca.file[0].downloadurl;
      let isForce = ca.file[0].isFoceUse;
      console.log("debugger：下载地址:", downloadUrl);
      console.log("debugger：是否强制更新:", isForce);
      await handlePluginUpdate(downloadUrl, isForce);
    }
  } catch (error) {
    console.error("获取插件更新配置失败", error);
    throw error;
  }
};

// 订阅插件更新事件
onMounted(async () => {
  try {
    await fetchPluginUpdateConfig();
  } catch (error) {
    console.error("初始化插件更新检查失败", error);
  }

  try {
    getAstsdk().getAppFun().regOnMiniPackStateEvent(bc);
    console.log("已经挂载监听插件包更新事件");
  } catch (error) {
    console.error("插件包更新事件订阅失败", error);
  }
});

// 启动倒计时（仅用于非强制更新）
const startCountdown = () => {
  countdown.value = 60;
  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      confirmUpdate();
    }
  }, 1000);
};

// 重置倒计时
const resetCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  startCountdown();
};

// 确认更新
const confirmUpdate = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  const appFun = getAstsdk().getAppFun();
  appFun.restartMe();
  showUpdate.value = false;
};

// 关闭更新提示
const closeUpdate = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  showUpdate.value = false;
};

// 关闭进度提示
const closeAlert = () => {
  logText.value = "";
};

type PluginUpdateState = {
  state: number;
  progress: number;
  log: string;
};

// 导出函数供外部使用
defineExpose({
  fetchPluginUpdateConfig,
});
</script>

<style scoped>
.progress-container {
  width: 100%;
  margin: 8px 0;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #4299e1;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 400px;
}

.modal-content h3 {
  margin: 0 0 16px;
  font-size: 18px;
}

.modal-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.modal-buttons button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.modal-buttons button.primary {
  background: #4299e1;
  color: white;
  border-color: #4299e1;
}

/* 更新进度提示样式 */
.update-alert {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 4px 8px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  min-width: 200px;
}

.alert-content {
  display: flex;
  align-items: center;
}

.alert-label {
  font-weight: 500;
  color: #374151;
  margin-right: 8px;
}

.alert-text {
  color: #6b7280;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #9ca3af;
  cursor: pointer;
  padding: 4px;
  line-height: 1;
  margin-left: 12px;
}

.close-btn:hover {
  color: #374151;
}

/* 更新提示卡片样式 */
.update-card {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 12px;
  min-width: 250px;
  max-width: 400px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px 12px;
  border-bottom: 1px solid #e5e7eb;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #111827;
}

.card-body {
  padding: 16px 20px 20px;
}

.update-message {
  margin: 0 0 16px;
  color: #374151;
  line-height: 1.5;
}

.countdown {
  font-weight: 600;
  color: #dc2626;
  font-size: 18px;
}

.button-group {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-secondary {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background: #e5e7eb;
}
</style>
